﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using DealKhuyenMaiV2.com.Models;
namespace DealKhuyenMaiV2.com.Helpers
{
    public class MyMembershipProvider : MembershipProvider
    {
        DKMDatabaseEntities dKMDataEntities = new DKMDatabaseEntities();
        public override string ApplicationName
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            if (!ValidateUser(username, oldPassword) || string.IsNullOrEmpty(newPassword.Trim()))
                return false;

            Account account = dKMDataEntities.Accounts.SingleOrDefault(t => t.Email == username);
            string hash = FormsAuthentication.HashPasswordForStoringInConfigFile(newPassword.Trim(), "md5");

            account.Password = hash;
            dKMDataEntities.SaveChanges();

            return true;
        }

        public  bool ChangeResetPassword(string username, string newPassword)
        {
            if (string.IsNullOrEmpty(newPassword.Trim()))
                return false;

            Account account = dKMDataEntities.Accounts.SingleOrDefault(t => t.Email == username);
            string hash = FormsAuthentication.HashPasswordForStoringInConfigFile(newPassword.Trim(), "md5");

            account.Password = hash;
            dKMDataEntities.SaveChanges();

            return true;
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            throw new NotImplementedException();
        }
        public void CreateUser(string email,string phonenumber, string password, int roleid, string _address, string _fullname, string _description, double _latitude, double _longitude)
        {

            if (string.IsNullOrEmpty(email.Trim()))
                throw new ArgumentException("The user name provided is invalid. Please check the value and try again.");
            if (string.IsNullOrEmpty(password.Trim()))
                throw new ArgumentException("The password provided is invalid. Please enter a valid password value.");
            if (string.IsNullOrEmpty(email.Trim()))
                throw new ArgumentException("The e-mail address provided is invalid. Please check the value and try again.");
            if (this.dKMDataEntities.Accounts.Any(user => user.Email == email))
                throw new ArgumentException("Username already exists. Please enter a different user name.");
          
            //    dKMDataEntities.ExecuteStoreCommand("SET IDENTITY_INSERT Account ON");
            Account acc = new Account()
            {
                Email = email,
                Password = FormsAuthentication.HashPasswordForStoringInConfigFile(password.Trim(), "md5"),
                IDTypeAccount = roleid,
                AddressReceive = _address,
                DateRegister = DateTime.Now,
                PhoneNumber=phonenumber,
                FullName = _fullname,
                Active=true,
                Description = _description,
                Longitude = _longitude,
                Latitude = _latitude,
            };
            if (UserExists(acc))
                throw new ArgumentException("User already exists");

            dKMDataEntities.Accounts.AddObject(acc);

            dKMDataEntities.SaveChanges();


        }

        public bool RoleExists(TypeAccount type)
        {
            if (type == null)
                return false;


            return (dKMDataEntities.TypeAccounts.SingleOrDefault(r => r.IDTypeAccount == type.IDTypeAccount || r.NameTypeAccount == type.NameTypeAccount) != null);
        }
        public bool UserExists(Account user)
        {
            if (user == null)
                return false;

            return (dKMDataEntities.Accounts.SingleOrDefault(u => u.Email == user.Email) != null);
        }
        public bool UserExists(string email)
        {
            if (email == null)
                return false;

            return (dKMDataEntities.Accounts.SingleOrDefault(u => u.Email == email) != null);
        }
        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            throw new NotImplementedException();
        }

        public override bool EnablePasswordReset
        {
            get { throw new NotImplementedException(); }
        }

        public override bool EnablePasswordRetrieval
        {
            get { throw new NotImplementedException(); }
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new NotImplementedException();
        }

        public override string GetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            throw new NotImplementedException();
        }

        public override string GetUserNameByEmail(string email)
        {
            throw new NotImplementedException();
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { throw new NotImplementedException(); }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { throw new NotImplementedException(); }
        }

        public override int MinRequiredPasswordLength
        {
            get
            {
                return 6;
            }
        }

        public override int PasswordAttemptWindow
        {
            get { throw new NotImplementedException(); }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { throw new NotImplementedException(); }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresUniqueEmail
        {
            get { throw new NotImplementedException(); }
        }

        public override string ResetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override bool UnlockUser(string userName)
        {
            throw new NotImplementedException();
        }

        public override void UpdateUser(MembershipUser user)
        {
            throw new NotImplementedException();
        }

        public override bool ValidateUser(string username, string password)
        {
            if (string.IsNullOrEmpty(password.Trim()) || string.IsNullOrEmpty(username.Trim()))
                return false;

            string hash = FormsAuthentication.HashPasswordForStoringInConfigFile(password.Trim(), "md5");
            IQueryable<Account> ALL = from account in dKMDataEntities.Accounts.Include("TypeAccount")
                                      orderby account.Email
                                      select account;
            return ALL.Any(account => (account.Email == username.Trim()) && (account.Password == hash) && account.TypeAccount.NameTypeAccount != "admin" &&account.Active==true);
        }
        public bool ValidateAdmin(string username, string password)
        {
            if (string.IsNullOrEmpty(password.Trim()) || string.IsNullOrEmpty(username.Trim()))
                return false;

            string hash = FormsAuthentication.HashPasswordForStoringInConfigFile(password.Trim(), "md5");
            IQueryable<Account> ALL = from account in dKMDataEntities.Accounts.Include("TypeAccount")
                                      orderby account.Email
                                      select account;
            return ALL.Any(account => (account.Email == username.Trim()) && (account.Password == hash) && account.TypeAccount.NameTypeAccount == "admin");
        }
    }
}